package com.ebn.mation.readagram;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.ebn.mation.readagram.gen.DaoMaster;
import com.ebn.mation.readagram.gen.DaoSession;

/**
 * 程序主入口
 *
 * @date 2024/1/22
 */
public class MyApplication extends Application {

    private static final String TAG = "MyApplication";

    private static Application sApplication;
    private DaoSession mDaoSession;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        sApplication = this;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "App launched >>> " + getAppVersion());

        initDb();
    }

    /**
     * greendao数据库初始化
     */
    private void initDb() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "readAgram.db");
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

    public String getAppVersion() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取 DaoSession
     *
     * @return DaoSession
     */
    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    /**
     * 获取应用上下文
     *
     * @return {@link Application}
     */
    public static Application getApp() {
        return sApplication;
    }
}
